from flask import request
from api.database import db
from api.apps.books import books_bp
from api.apps.books.models import Book
from api.apps.books.schemas import BookSchema
from api.apps.utils.responses import response_with
from api.apps.utils import responses as resp
from flask_jwt_extended import jwt_required


@books_bp.route('/', methods=['POST'])
def create_book():
  try:
    data = request.get_json()
    book_schema = BookSchema()
    book = book_schema.load(data)
    result = book_schema.dump(book.create())
    return response_with(resp.SUCCESS_201, value={"book": result})
  except Exception as e:
    print(f"Error: {e}")
    return response_with(resp.INVALID_INPUT_422)


@books_bp.route('/', methods=['GET'])
@jwt_required()
def get_book_list():
  fetched = Book.query.all()
  book_schema = BookSchema(many=True)
  books = book_schema.dump(fetched)
  return response_with(resp.SUCCESS_200, value={"books": books})


@books_bp.route('/<int:id>', methods=['GET'])
def get_book_detail(id):
  fetched = Book.query.get_or_404(id)
  book_schema = BookSchema()
  books = book_schema.dump(fetched)
  return response_with(resp.SUCCESS_200, value={"books": books})


@books_bp.route('/<int:id>', methods=['PUT'])
def update_book_detail(id):
  data = request.get_json()
  get_book = Book.query.get_or_404(id)
  get_book.title = data['title']
  get_book.year = data['year']
  get_book.author_id = data['author_id']
  db.session.add(get_book)
  db.session.commit()
  book_schema = BookSchema()
  book = book_schema.dump(get_book)
  return response_with(resp.SUCCESS_200, value={"book": book})


@books_bp.route('/<int:id>', methods=['PATCH'])
def modify_book_detail(id):
  # 获取请求数据，如果数据为空或格式错误，返回 400 错误
  data = request.get_json() or {}
  if not data:
    return response_with(resp.BAD_REQUEST_400, message="No data provided")

  # 查询书籍，如果不存在则返回 404 错误
  book = Book.query.get_or_404(id)

  # 更新书籍信息
  if 'title' in data:
    book.title = data['title']
  if 'year' in data:
    book.year = data['year']

  # 提交更改到数据库
  db.session.add(book)
  db.session.commit()

  # 序列化书籍对象并返回响应
  book_schema = BookSchema()
  result = book_schema.dump(book)
  return response_with(resp.SUCCESS_200, value={"book": result})


@books_bp.route('/<int:id>', methods=['DELETE'])
def delete_books(id):
  get_book = Book.query.get_or_404(id)
  db.session.delete(get_book)
  db.session.commit()
  return response_with(resp.SUCCESS_200)
